package com.linkdood.app.service.impl;


import com.alibaba.fastjson.JSON;
import com.jayway.jsonpath.JsonPath;
import com.linkdood.app.constants.ErrorCode;
import com.linkdood.app.domain.ThirdParty;
import com.linkdood.app.exception.GeneralException;
import com.linkdood.app.service.TokenService;
import com.linkdood.app.service.ThirdPartyService;
import com.linkdood.app.service.dto.HsgRequestDTO;
import com.linkdood.app.service.dto.HsgTokenDTO;
import com.linkdood.app.utils.DdioUtil;
import com.linkdood.app.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;


/**
 * 该类封装了 ddio 和 好社工平台 获取 token 的方法
 *
 * @author lxy
 */
@Slf4j
@Service
public class TokenServiceImpl implements TokenService {

    @Value("${hsg.url}")
    private String hsgUrl;
    @Value("${hsg.appId}")
    private String appId;
    @Value("${hsg.secret}")
    private String secret;

    private static final String HSG_TOKEN_URL = "/api/login/app";


    /**
     * 获取 ddio access_token
     */
    @Override
    @Cacheable(value = "accessToken", key = "#thirdParty.getAppId()", condition = "#thirdParty != null")
    public String accessToken(ThirdParty thirdParty) {
        log.debug("Enter accessToken with cache. thirdParty = {}", thirdParty);
        String accessToken;
        ResponseEntity<String> entity = DdioUtil.getAccessTokenResponse(thirdParty);
        Integer code = JsonPath.parse(entity.getBody()).read("$.code");
        if (!Objects.equals(code, 0)) {
            throw new GeneralException(ErrorCode.ERROR_DDIO);
        }
        accessToken = JsonPath.parse(entity.getBody()).read("$.result.access_token");
        if (StringUtils.isEmpty(accessToken)) {
            throw new GeneralException(ErrorCode.ERROR_DDIO);
        }
        return accessToken;
    }


    @Cacheable(value = "hsgToken", key = "#root.methodName")
    public String hsgToken() {
        HsgRequestDTO hsgRequestDTO = new HsgRequestDTO();
        hsgRequestDTO.setAppId(appId);
        hsgRequestDTO.setAppSecret(secret);
        String urlData = hsgUrl + HSG_TOKEN_URL;
        ResponseEntity<String> responseEntity = HttpUtil.postRestTemplate(urlData, hsgRequestDTO, new HttpHeaders());
        log.debug("hsg service account , platRequestDTO = {}", hsgRequestDTO);
        if (responseEntity.getStatusCodeValue() != HttpStatus.OK.value()) {
            log.error("unified service account login error, StatusCode = {}", responseEntity.getStatusCodeValue());
            throw new RuntimeException("获取好社工平台token失败！");
        }
        HsgTokenDTO hsgTokenDTO = JSON.parseObject(responseEntity.getBody(), HsgTokenDTO.class);
        log.debug("unified service token, token = {}", hsgTokenDTO.getToken());
        return hsgTokenDTO.getToken();
    }


}
